<template>
  <a-modal
    width="450px"
    v-model:visible="visible"
    :mask-closable="false"
    title="自定义标签"
    @cancel="close"
    @close="close"
    unmount-on-close
  >
    <page-form layout="vertical">
      <page-form-row :gutter="24">
        <page-form-item field="endTime" label="标签" size="1">
          <sysdict-select
            v-model="data.customLabelList"
            multiple
            :popupContainer="'#app'"
            code="short_order_custom_label"
            @change="onSysdictSelectChange"
            :maxLength="10"
            allow-clear
          />
        </page-form-item>
      </page-form-row>
    </page-form>
    <template #footer>
      <a-button @click="close">关闭</a-button>
      <a-button type="primary" @click="ok" :loading="loading">确认</a-button>
    </template>
  </a-modal>
</template>

<script setup lang="ts">
  import { ref, computed } from 'vue'
  import { addCustomTag } from '@/api/order/sOrder'
  import { addCustomLabel } from '@/api/order/czsOrder'
  import { Notification } from '@arco-design/web-vue'

  const props = defineProps({
    modelValue: {
      type: Boolean,
      default: false,
    },
    orderType: {
      type: Number,
      default: 1, // 1: 短租 2: 长租
    },
  })

  const data = ref<any>({})
  const loading = ref(false)
  const selectKeys = ref<string[] | number[]>([])

  const emits = defineEmits(['update:modelValue', 'ok'])
  const visible = computed({
    get: () => props.modelValue,
    set: (value) => emits('update:modelValue', value),
  })

  const onSysdictSelectChange = (val: number[], label: string) => {
    console.log('onSysdictSelectChange: ', val, label)
    selectKeys.value = val
  }

  const open = (record: any) => {
    console.log('custom-tag-modal: ', record)
    data.value = record
    selectKeys.value = record.customLabelList || []
  }

  const ok = () => {
    loading.value = true

    if (props.orderType == 1) {
      addCustomTag({
        id: data.value.id,
        customLabelList: selectKeys.value,
      })
        .then(() => {
          Notification.success('添加成功')
          close()
          emits('ok')
        })
        .catch(() => {
          Notification.error('添加失败')
        })
        .finally(() => {
          loading.value = false
        })
    } else {
      addCustomLabel({
        id: data.value.id,
        customLabelList: selectKeys.value,
      })
        .then(() => {
          Notification.success('添加成功')
          close()
          emits('ok')
        })
        .catch(() => {
          Notification.error('添加失败')
        })
        .finally(() => {
          loading.value = false
        })
    }
  }

  const close = () => {
    visible.value = false
    loading.value = false
    selectKeys.value = []
    data.value = {}
  }

  defineExpose({
    open,
  })
</script>

<style lang="less" scoped></style>
